// 这种解法没啥用，时间复杂度太高
var Trie = function () {
  this.map = {}
};

/** 
 * @param {string} word
 * @return {void}
 */
Trie.prototype.insert = function (word) {
  this.map[word] = 1
};

/** 
 * @param {string} word
 * @return {boolean}
 */
Trie.prototype.search = function (word) {
  if (this.map[word]) return true
  return false
};

/** 
 * @param {string} prefix
 * @return {boolean}
 */
Trie.prototype.startsWith = function (prefix) {
  for (let k in this.map) {
    if (k.startsWith(prefix)) return true
  }
  return false
};
/**
 * Your Trie object will be instantiated and called as such:
 * var obj = new Trie()
 * obj.insert(word)
 * var param_2 = obj.search(word)
 * var param_3 = obj.startsWith(prefix)
 */

// 用这种解法，实质上就是一个多叉树
// 将a-z映射到数组的每一个位置
class TrieNode {
  constructor() {
    this.isEnd = false
    this.next = new Array(26).fill(null)
  }
}
var Trie = function () {
  this.root = new TrieNode()
};

/** 
 * @param {string} word
 * @return {void}
 */
Trie.prototype.insert = function (word) {
  let temp = this.root
  for(let i = 0; i < word.length; i++) {
    let inx = word[i] - 'a'
    if(temp.next[inx] == null) temp.next[inx] = new TrieNode()
    temp = temp.next[inx]
  }
  temp.isEnd = true
};

/** 
 * @param {string} word
 * @return {boolean}
 */
Trie.prototype.search = function (word) {
  let temp = root
  for(let i = 0; i < word.length; i++) {
    let inx = word[i] - 'a'
    if(temp.next[inx] == null) return false
    temp = temp.next[inx]
  }
  return temp.isEnd
};

/** 
 * @param {string} prefix
 * @return {boolean}
 */
Trie.prototype.startsWith = function (prefix) {
  let temp = root
  for(let i = 0; i < prefix.length; i++) {
    let inx = prefix[i] - 'a'
    if(temp.next[inx] == null) return false
    temp = temp.next[inx]
  }
  return true
};

/**
 * Your Trie object will be instantiated and called as such:
 * var obj = new Trie()
 * obj.insert(word)
 * var param_2 = obj.search(word)
 * var param_3 = obj.startsWith(prefix)
 */